import { getLastEvent } from "./getLastEvent";

/**
 * [<div/>, <div id='a'/>, <div class='b'/>] --> ['div', 'div#a', 'div.b']
 */
export const getComposedPath = (e) => { 
  if (!e) return [];
  const composedPathEle = getComposedPathEle(e.target); // return [<div/>, <div id='a'/>, <div class='b'/>] 

  const composedPath = composedPathEle.reverse().slice(2).map(ele => { 
    let selector = ele.tagName.toLowerCase();
    if (ele.id) { 
      selector += `#${ele.id}`;
    }
    if (ele.className) { 
      selector += `.${ele.className}`;
    }
    return selector;
  });

  return composedPath;
}
/**
 * e: event
 * ['div', 'div#a', 'div.b'] --> 'div > div#a > div.b'
 */
export const getPath = () => { 
  const e = getLastEvent() // 报错时, 最后一个触发的事件
  if (!e) return '';
  const composedPath = getComposedPath (e); // return ['div', 'div#a', 'div.b'] 
  const selectors = composedPath.join(' > ');
  return selectors; // 'div > div#a > div.b'
}

// 既不支持 .path
// 也不支持 .composedPath()
// 就通过dom节点依次向上找
/// target: dom节点
// return [<div/>, <div id='a'/>, <div class='b'/>] 
function getComposedPathEle(target) {
  const nodes = []

  while (target && target.parentNode) {
    nodes.push(target)
    target = target.parentNode
  }

  return [...nodes, document, window]
}
